package com.bdweb.service.impl;
import com.bdweb.dao.impl.powerAllDaoImpl;
import com.bdweb.model.POWER;
import com.bdweb.pojo.Result;
import com.bdweb.service.PowerAllService;
import com.bdweb.mokuai.UDPClient1;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;


@Service
public class PowerAllServiceImpl implements PowerAllService {
    @Autowired
   private powerAllDaoImpl powerAllDaoImpl;
    @Autowired
   private MySqlUpdater mySqlUpdater;
    @Override
    public Result listPowerOpenAll() throws IOException, InterruptedException {

        return getPowerSwitch(0);
    }

    @Override
    public Result listPowerCloseAll() throws IOException, InterruptedException {
        return getPowerSwitch(1);
    }

    private Result getPowerSwitch(int id) throws IOException, InterruptedException {
        List<POWER> allPower = powerAllDaoImpl.list();

        //所有电箱全开或关


        for (int i = 0; i < allPower.size(); i++) {
            if(id==0){
                new UDPClient1(allPower.get(i).getCodeopen()+"\r\n", allPower.get(i).getIp(), Integer.parseInt(allPower.get(i).getPort()));
                mySqlUpdater.updateValueAllOpen("bd_power","isopen",1);
                Thread.sleep(200);

            }if(id==1){
                new UDPClient1(allPower.get(i).getCodeclose()+"\r\n", allPower.get(i).getIp(), Integer.parseInt(allPower.get(i).getPort()));
                mySqlUpdater.updateValueAllOpen("bd_power","isopen",0);
                Thread.sleep(200);
            }

        }
        return new Result(200, "success", id==0?"电箱全部开启OK":"电箱全部关闭OK");
    }


}
